const $ = function (el) {
  try {
    const item = document.querySelectorAll(el)
    return item.length === 1 ? item[0] : item
  } catch (err) {
    console.log(err)
  }
}

let empileCardCount = 0

function cssFormatter (dataSlideIndex, counts) {
  const centerCount = counts % 2 === 0 ? Math.floor(counts / 2) - 1 : Math.floor(counts / 2)
  for (let i = 0; i < counts; i++) {
    const node = $(`li[${dataSlideIndex}='${i}']`)
    const classes = node.classList
    if (classes.contains('left-card')) {
      if (i < centerCount) {
        classes.replace('left-card', 'left-card')
      } else if (i > centerCount) {
        classes.replace('left-card', 'right-card')
      } else {
        classes.replace('left-card', 'center-card')
      }
    } else if (classes.contains('right-card')) {
      if (i < centerCount) {
        classes.replace('right-card', 'left-card')
      } else if (i > centerCount) {
        classes.replace('right-card', 'right-card')
      } else {
        classes.replace('right-card', 'center-card')
      }
    } else if (classes.contains('center-card')) {
      if (i < centerCount) {
        classes.replace('center-card', 'left-card')
      } else if (i > centerCount) {
        classes.replace('center-card', 'right-card')
      } else {
        classes.replace('center-card', 'center-card')
      }
    } else {
      if (i < centerCount) {
        classes.add('left-card')
      } else if (i > centerCount) {
        classes.add('right-card')
      } else {
        classes.add('center-card')
      }
    }
  }
}

export function initCard (length) {
  empileCardCount = length
  const instance = new window.Empile($('.demo1>.container'), {
    autoplay: {
      delay: 2600,
      docHiddenOff: true
    },
    waitForTransition: false,
    isClickSlide: true,
    navigation: {
      nextEl: $('.demo1 .btn-right'),
      prevEl: $('.demo1 .btn-left')
    },
    on: {
      // 卡片切换时执行
      slideChange: function () {
        // 设置'当前显示的是第[xxx]张'元素的文本内容
        cssFormatter(this.slides.dataSlideIndex, empileCardCount)
      }
    },
    pagination: {
      el: document.querySelector('.navigation'),
      clickable: true,
      bulletClass: 'dot',
      bulletActiveClass: 'active'
    },
    css: function (coord, absCoord, index) {
      const zIndex = 100 - absCoord
      const opacity = Math.pow(1, absCoord).toFixed(1)
      const scale = 'scale(' + Math.pow(0.9, absCoord).toFixed(2) + ')'
      const translateX = 'translateX(' + (1664 / empileCardCount) * coord + 'px)'

      const transform = [translateX, scale].join(' ')
      return {
        zIndex: zIndex,
        opacity: (empileCardCount % 2 === 0) && index === (empileCardCount - 1) ? 0 : opacity,
        transform: transform,
        visibility: (empileCardCount % 2 === 0) && index === (empileCardCount - 1) ? 'hidden' : 'visible'
      }
    }

  })
  cssFormatter(instance.slides.dataSlideIndex, empileCardCount)
  return instance
}
